local filelog = require "filelog"

--有牛牌表
local cowcards_list = require "cowcards_list"

require "zrbrnnenum"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

--扑克牌定义
--百位表示花色：1方块 2梅花 3红桃 4黑桃;末2位表示牌值1-A 11-J 12-Q 13—K 2~10-2~10
local CardData = {
    101,102,103,104,105,106,107,108,109,110,111,112,113,
    201,202,203,204,205,206,207,208,209,210,211,212,213,
    301,302,303,304,305,306,307,308,309,310,311,312,313,
    401,402,403,404,405,406,407,408,409,410,411,412,413,
}

--特殊奖励定义
local SpecialPrize = {
    SPECIAL_PRIZE_MEI_NIU = 0,          --没牛
    SPECIAL_PRIZE_NIU_YI = 1,           --牛一
    SPECIAL_PRIZE_NIU_ER = 2,           --牛二
    SPECIAL_PRIZE_NIU_SAN = 3,          --牛三
    SPECIAL_PRIZE_NIU_SI = 4,           --牛四
    SPECIAL_PRIZE_NIU_WU = 5,           --牛五
    SPECIAL_PRIZE_NIU_LIU = 6,          --牛六
    SPECIAL_PRIZE_NIU_QI = 7,           --牛七
    SPECIAL_PRIZE_NIU_BA = 8,           --牛八
    SPECIAL_PRIZE_NIU_JIU = 9,          --牛九
    SPECIAL_PRIZE_NIU_NIU = 10,         --牛牛
    SPECIAL_PRIZE_SHUNZI_NIU = 11,      --顺子牛
    SPECIAL_PRIZE_TONGHUA_NIU = 12,     --同花牛
    SPECIAL_PRIZE_HULU_NIU = 13,        --葫芦牛
    SPECIAL_PRIZE_ZHADAN_NIU = 14,      --炸弹牛
    SPECIAL_PRIZE_WUHUA_NIU = 15,       --五花牛
    SPECIAL_PRIZE_WUXIAO_NIU = 16,      --五小牛
    SPECIAL_PRIZE_TONGHUASHUN_NIU = 17, --同花顺牛
}

-------------------------

local CardTool = { }

local CardColor = {
	diamonds = 1,	--方块
	clubs = 2,		--梅花
	hearts = 3,		--红桃
	spades = 4,		--黑桃
}

-----------------------------------

--
--检测是否为有牛牌型
--
local function check_is_cowcards(cards, sv)
    if not cards or #cards ~= 5 then
        return
    end

    local str = ""
    if not sv then
        sv = {}
        for _,v in pairs(cards) do
            local cv = v % 100
            table.insert(sv,cv)
        end
        table.sort(sv)
    end

    for _,cv in pairs(sv) do
        if cv < 10 then
            str = str .. cv
        else
            str = str .. 'A'
        end
    end
    
    return cowcards_list[str]
end

--
--获得牌型：同花顺牛，五小牛，五花牛，炸弹牛，葫芦牛，同花牛，顺子牛，牛一~牛牛，没牛
--17同花顺 16五小牛 15五花牛 14炸弹牛 13葫芦牛 12同花牛 11顺子牛 1~10牛一~牛牛 0没牛
--
function CardTool.get_cards_type(cards, is_special)
    if not cards or #cards ~= 5 then
        return
    end

    local result = {}

    --排序牌值
    local cvs = {}
    local points = 0
    local maxcard = 0
    local specard = 0
    local is_samecolor = nil
    for _,v in pairs(cards) do
        local ct = math.floor(v / 100)
        local cv = v % 100
        table.insert(cvs,cv)
        is_samecolor = is_samecolor or ct
        if is_samecolor ~= ct then
            is_samecolor = 0
        end
        if cv > 10 then
            points = points + 10
        else
            points = points + cv
        end
        local mcv = maxcard % 100
        if mcv < cv then
            maxcard = v
        elseif mcv == cv and 
        math.floor(maxcard / 100) < ct then
            maxcard = v
        end
    end
    table.sort(cvs)

    --特殊牛
    local is_sz = false
    local is_th = false
    
     --检测特殊牛：顺子牛,同花牛,葫芦牛,同花顺牛
    if is_special then
        --判断是否为顺子牛
        if (cvs[5] - cvs[1] == 4 and cvs[4] - cvs[1] == 3)
        and (cvs[3] - cvs[1] == 2 and cvs[2] - cvs[1] == 1) then
            is_sz = true
            result.cards_type = SpecialPrize.SPECIAL_PRIZE_SHUNZI_NIU
        end

        --判断是否为同花牛
        if is_samecolor ~= 0 then
            is_th = true
            result.cards_type = SpecialPrize.SPECIAL_PRIZE_TONGHUA_NIU
        end

        --判断是否为葫芦牛
        if not is_th and not is_sz then
            if (cvs[1] == cvs[3] and cvs[4] == cvs[5]) 
            or (cvs[1] == cvs[2] and cvs[3] == cvs[5]) then
                is_hl = true
                result.cards_type = SpecialPrize.SPECIAL_PRIZE_HULU_NIU
            end
        end
    end

    --判断是否为炸弹牛
    if (cvs[1] == cvs[4] or cvs[2] == cvs[5]) then
        specard = cvs[2]
        result.cards_type = SpecialPrize.SPECIAL_PRIZE_ZHADAN_NIU
    end
    
    --判断是否为五花牛
    if cvs[1] > 10 then
        result.cards_type = SpecialPrize.SPECIAL_PRIZE_WUHUA_NIU
    end

    --判断是否为五小牛
    if (points < 11 and cvs[5] < 6) then
        result.cards_type = SpecialPrize.SPECIAL_PRIZE_WUXIAO_NIU
    end

    --判断是否为同花顺牛
    if is_th and is_sz then
        result.cards_type = SpecialPrize.SPECIAL_PRIZE_TONGHUASHUN_NIU
    end

    --判断是否为牛一~牛牛
    --任3张牌点数和为10,20或30即有牛
    --a + b + c = 10
    --a + b + c = 20
    --a + b + c = 30
    if not result.cards_type then
        local niu_num = check_is_cowcards(cards, cvs)
        if not niu_num then
            result.cards_type = SpecialPrize.SPECIAL_PRIZE_MEI_NIU
        else
            result.cards_type = niu_num
        end
    end

    --返回结果
    result.spe_card = specard
    result.max_card = maxcard
    result.points = points % 10
    if result.points == 0 then
        result.points = 10
    end

    return result
end

--比较玩家牌
--true 闲赢 false 庄赢
function CardTool.compare_cards(banker_cards, player_cards)
    if not banker_cards or not player_cards then
        return
    end

    if banker_cards.cards_type ~= player_cards.cards_type then      --比较牌型
        return (banker_cards.cards_type < player_cards.cards_type)
    elseif banker_cards.cards_type == SpecialPrize.SPECIAL_PRIZE_ZHADAN_NIU then    --炸弹牛，比较炸弹大小
        return (banker_cards.spe_card < player_cards.spe_card)
    else    --牌型相同比较最大单牌
        local bcv = banker_cards.max_card % 100
        local pcv = player_cards.max_card % 100
        if bcv ~= pcv then return (bcv < pcv) end
        return (banker_cards.max_card < player_cards.max_card)
    end
end

--转换牌数据
function CardTool.convert_cards(cards)
	local all_cards = {
		[1] = {},
		[2] = {},
		[3] = {},
		[4] = {},
	}
	local dice_nums = {}

	local is_flag = false	
	for _, carditem in ipairs(cards) do
		if carditem.status == "open" then
			local ct = CardColor[carditem.suit] or 0
			local cv = math.floor(tonumber(carditem.point))
            local card = ct * 100 + cv
			local ty = string.sub(carditem.type, 1, 1)
			if ty == "p" then
				local i = tonumber(string.sub(carditem.type, -1, -1))
				table.insert(all_cards[i+1], card)
			elseif ty == "b" then
				table.insert(all_cards[1], card)
			elseif ty == "d" then
				table.insert(dice_nums, card)
			end
			is_flag = true
		end
	end
	
	if not is_flag then
		return {}
	end
	
	return all_cards, dice_nums
end

--获得开牌结果
function CardTool.get_opencardresult(gameData)
	--转换牌数据
	local all_cards = CardTool.convert_cards(gameData.cardInfo)
	if #all_cards == 0 then
		return false
    end
    
    local isdicecard = true
    for _, cards in ipairs(all_cards) do
        if #cards > 0 then
            isdicecard = false
            break
        end
    end
    if isdicecard then return false end
	
	local all_results = {}
	for i,cards in pairs(all_cards) do
	   all_results[i] = CardTool.get_cards_type(cards)
	end
	
	local result_list = {
		all_cards = all_cards,
		all_results = all_results,
	}
	
	return result_list
end

--获得摇骰子结果
function CardTool.get_dicesresult(gameData)
	--转换牌数据
	local _, dice_nums = CardTool.convert_cards(gameData.cardInfo)
	
	return dice_nums
end

--获得游戏结果
function CardTool.get_gameresult(gameResult)
    local ext_prize_list = {}
	
	--转换牌数据
	local all_cards = CardTool.convert_cards(gameResult.cards)
	local all_results = {}
	for i, cards in pairs(all_cards) do
	   all_results[i] = CardTool.get_cards_type(cards)
    end
     --判定开奖结果，第一副牌为庄家牌，其他4副为闲家
     for i = 2, 4 do
        local is_win = CardTool.compare_cards(all_results[1], all_results[i])
        all_results[i].is_win = is_win
    end
	
	--判定开奖结果，第一副牌为庄家牌，其他3副为闲家
	local winners = json.decode(gameResult.winner)
	if winners.player1 == "player" then
		table.insert(ext_prize_list, EBRNNBetBtnId.BET_BTN_ID_PLAYER_ONE)
	end
	if winners.player2 == "player" then
		table.insert(ext_prize_list, EBRNNBetBtnId.BET_BTN_ID_PLAYER_TWO)
	end
	if winners.player3 == "player" then
		table.insert(ext_prize_list, EBRNNBetBtnId.BET_BTN_ID_PLAYER_THREE)
	end

	--庄通杀
	if #ext_prize_list == 0 then
		table.insert(ext_prize_list, EBRNNExtraPrizeType.EXTRA_PRIZE_TYPE_KILLALL)
	end
	
	local result_list = {
		all_cards = all_cards,
		all_results = all_results,
		prize_id = 0,
		ext_prize_list = ext_prize_list,
	}
	-- filelog.print("get_gameresult data = ", result_list)
	return result_list
end

return CardTool
